import axios from 'axios'
import store from '@/store/store.js'
import * as types from './store/types'
import router from './router/index'

// axios 配置

axios.defaults.timeout = 10000;
// axios.defaults.baseURI = '';

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    // token = window.localStrage.getItem('token');
    if (store.state.token) {
    	config.headers.Authorization = `token ${store.state.token}`;
    }
    return config;
  }, function (error) {
    // 对请求错误做些什么
    console.log(222);
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    console.log('响应错误')
    if (error.response) {

    	switch(error.response.status) {
    		case 401:
    			// 返回 401 清除token信息并跳转到登录页面
    			store.commit(types.LOGOUT);
    			router.replace({
    				path:'login',
    				query:{redirect:router.currentRoute.fullPath}
    			})
    	}
    }
    console.log(error);
    return Promise.reject(error);
  });

export default axios;